package com.itsu.shirojwt.shiro.filter;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.itsu.shirojwt.response.ResObj;
import com.itsu.shirojwt.shiro.token.JWTToken;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JWTFilter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(final ServletRequest request, final ServletResponse response)
            throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String tokenStr = httpRequest.getHeader("token");
        JWTToken jwtToken = new JWTToken(tokenStr);
        return jwtToken;
    }

    @Override
    protected boolean onAccessDenied(final ServletRequest request, final ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String msg = (String) httpRequest.getAttribute("error");

        try (PrintWriter writer = response.getWriter()) {
            writer.write(JSONUtil.toJsonStr(ResObj.noAuthen(msg)));
        } catch (Exception e) {
            throw e;
        }
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginRequest(request, response))
            return true;
        boolean allow = false;
        try {
            allow = executeLogin(request, response);
        } catch (Exception e) {
            log.error("Error happened ", e);
        }
        return allow || super.isPermissive(mappedValue);
    }

}